package com.phonegap.extensions;


import java.io.BufferedReader;
import java.io.InputStreamReader;


public class PreProcessor {

	private static PreProcessor instance;
	private java.util.Hashtable<String, ICommandExecutor> executors;
	private android.webkit.WebView appView;
	
	
	
	
	public PreProcessor(android.webkit.WebView appView) {
		executors = new java.util.Hashtable<String, ICommandExecutor>();
		this.appView = appView;
	}
	
	
	public static PreProcessor getInstance(android.webkit.WebView appView) {
		if(instance==null) {
			instance = new PreProcessor(appView);
			ICommandExecutor executor = new CommandIncludeExecutor();
			instance.registerCommandExecutor("include", executor);
			
		}
			
		
		return instance;
	}
	
	public boolean shouldMakePreProcess(String url) {
		if(url.startsWith("file:")&& (url.endsWith(".html")| url.endsWith(".htm"))) 
			return true;
		return false;
	}
	
	
	public void loadUrl(String url) {
		
		String html = loadHtmlFile(url, appView);
		String mimeType="text/html";
		String encoding = "utf-8";
		appView.loadDataWithBaseURL("file:///android_asset/www/", html, mimeType, encoding, null);

	
	}
	
	protected String loadHtmlFile(String url, android.webkit.WebView appView) {
		String html = ""; 
		
		try {
			
			
			String arquivoHtml = url.substring(url.lastIndexOf("/")+ 1);
			
			
			android.content.res.AssetManager mgr = appView.getContext().getAssets();
			
			java.io.InputStream in = mgr.open("www/" + arquivoHtml); 
			StringBuffer inLine = new StringBuffer(); 
			
			
			InputStreamReader isr = new InputStreamReader(in); 
			
			String text;
			BufferedReader inRd = new BufferedReader(isr); 
			
			        
			while ((text = inRd.readLine()) != null) { 
				
				
				
				if(isCommand(text)) {
					String command = processCommand(text);
					inLine.append(command); 
					inLine.append("\n"); 
				}
				else {
					inLine.append(text); 
					inLine.append("\n"); 
					
				}
			} 
			in.close(); 
			html =  inLine.toString();

		} catch (Exception e) {
			html = e.toString();
		}		

		
		return html;
	}	
	
	protected boolean isCommand(String expression) {
		int position = expression.indexOf("phonegap");
		
		if(position > 0 ) {
			return true;
		}
		
		
		return false;
		
	}
	
	
	protected String processCommand(String expression) {
		String commandText = expression.substring(expression.indexOf("<phonegap"), expression.indexOf("/>") + 2);
		Command cmd = Command.parseCommand(commandText);
		
		ICommandExecutor executor = getCommandExecutor(cmd);
		
		
		
		
		if(executor == null) {
			return "<font color='red'>There is no command executor for the command: '" + android.text.TextUtils.htmlEncode(expression) +  "'</font>";
			
			
		}
		return executor.process();
		
	}	
	
	public void registerCommandExecutor(String commandName, ICommandExecutor executor) {
		executors.put(commandName, executor);
		
	}
	
	public ICommandExecutor getCommandExecutor(Command cmd) {
		ICommandExecutor executor = executors.get(cmd.getName());
		executor.setCommand(cmd);
		executor.setAppView(appView);
		return executor;
		
	}
}
